package com.rs.adminweb.admin.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.jaxplat.commons.Row;
import com.jaxplat.util.StringUtils;
import com.rs.adminweb.admin.delegate.AdminDelegate;
import com.rs.adminweb.admin.entity.AdminEntity;
import com.rs.adminweb.commons.util.EncryptDES;
import com.rs.commons.web.AdminBaseAction;
import com.rs.util.MD5;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;

public class LoginAction extends AdminBaseAction
{
    private Log log = LogFactory.getLog(this.getClass());

    private AdminDelegate adminDelegate;

    public AdminDelegate getAdminDelegate()
    {
        return adminDelegate;
    }

    public void setAdminDelegate(AdminDelegate adminDelegate)
    {
        this.adminDelegate = adminDelegate;
    }

    /**
     * 查询用户列表
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView userList(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Row param = this.parseRequestParametersToRow(request);
        // 用户表主键编号
        if (!"".equals(param.getString("id")) && null != param.getString("id"))
        {
            param.put("id", param.getString("id"));
        }
        Object[] list = this.getAdminDelegate().getUserList(param);
        EncryptDES des = new EncryptDES();
        List newList = new ArrayList();
        List listDto = (List) list[0];
        for (int i = 0; i < listDto.size(); i++)
        {
            Map adminEntity = (Map) listDto.get(i);
            adminEntity.put("login_id", (String) adminEntity.get("login_id"));
            adminEntity.put("password", (String) adminEntity.get("password"));
            newList.add(adminEntity);
        }
        JSONObject json = new JSONObject();
        // 这里必须写死为rows和total
        // 否则页面不显示
        json.element("total", ((Integer) list[1]).intValue());
        json.element("rows", ((List) list[0]));
        json.element("msg", request.getAttribute("msg"));
        if (null != request.getAttribute("againFlag") && !"".equals(request.getAttribute("againFlag")))
        {
            json.element("againFlag", request.getAttribute("againFlag"));
        }
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print(json.toString());
        response.getWriter().flush();
        response.getWriter().close();
        return null;
    }

    public ModelAndView deleteUser(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Row param = this.parseRequestParametersToRow(request);
        // 删除操作
        int count = this.adminDelegate.deleteUser(param);
        JSONObject json = new JSONObject();
        String message = "";
        if (count == 0)
        {
            message = "删除失败";
        }
        else
        {
            message = "删除成功";
        }
        json.element("Message", message);
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print(json.toString());
        response.getWriter().flush();
        response.getWriter().close();
        return null;
    }

    /**
     * 添加用户
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView addUser(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Row param = this.parseRequestParametersToRow(request);
        AdminEntity adminEntity = new AdminEntity();
        EncryptDES des = new EncryptDES();
        String id = request.getParameter("id");
        adminEntity.setLoginId(request.getParameter("loginId"));
        // 查询数据库中是否存在该用户
        String msg = "保存失败！";
        param.put("loginId", request.getParameter("loginId"));
        Object[] list = this.getAdminDelegate().getUserList(param);
        List listDto = (List) list[0];
        adminEntity.setName(request.getParameter("name"));
        adminEntity.setPassword(MD5.md5(request.getParameter("password")));
        adminEntity.setPerms(request.getParameter("prems"));
        adminEntity.setType(request.getParameter("type"));
        adminEntity.setLoginTime(new Date());
        adminEntity.setLogoutTime(new Date());
        // 如果ID不为空则修改该条记录
        if (null != id && id.length() > 0)
        {
            adminEntity.setId(Long.parseLong(id));
            int count = this.adminDelegate.getAdminDao().updateUser(adminEntity);
            if (count > 0)
            {
                msg = "更新成功！";
            }
        }
        else if ("".equals(id))
        {// 保存记录
            if (listDto.size() == 0)
            {
                AdminEntity entity = this.adminDelegate.getAdminDao().addUser(adminEntity);
                if (null != entity)
                {
                    msg = "保存成功！";
                }
            }
            else
            {
                msg = "数据库中已存在该用户，请重新录入。";
                request.setAttribute("againFlag", "1");
            }

        }
        request.setAttribute("msg", msg);
        userList(request, response);
        return null;
    }

    /**
     * 用户登录
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        HttpSession session = request.getSession(true);
        Map map = new HashMap();
        Map userMap = new HashMap();
        Map userInfo = (Map) session.getAttribute("userMap");
        // 后台生成的验证
        String cver_code = (String) session.getAttribute("cver_code");
        if (null != userInfo)
        {
            log.info("user has session.");
            return new ModelAndView("mainframe", userMap);
        }

        else if (StringUtils.isEmpty(request.getParameter("loginId")) || StringUtils.isEmpty(request.getParameter("loginId"))
                || StringUtils.isEmpty(request.getParameter("number")))
        {
            log.debug("loginId: " + request.getParameter("loginId"));
            log.debug("cver_code: " + request.getParameter("number"));
            log.info("loginId, cver_code validate failed.");
            return new ModelAndView("login");
        }
        else
        {
            try
            {
                log.info("user begin login.");

                AdminEntity adminEntity = new AdminEntity();
                String user_code = request.getParameter("number");
                // 对用户输入的用户名密码进行DES加密(防止sql注入)
                EncryptDES des = new EncryptDES();
                log.info("loginId:" + request.getParameter("loginId"));
                log.info("password:" + request.getParameter("password"));
                String loginId = request.getParameter("loginId");
                String password = MD5.md5(request.getParameter("password"));
                adminEntity.setLoginId(loginId);
                adminEntity.setPassword(password);
                String message = "";
                if (!StringUtils.isEmpty(request.getParameter("loginId")) && !StringUtils.isEmpty(request.getParameter("password"))
                        && !StringUtils.isEmpty(request.getParameter("number")))
                {
                    Row row = this.adminDelegate.getAdminDao().login(adminEntity);
                    if (null != row && cver_code.equals(user_code))
                    {
                        Iterator iterator = row.entrySet().iterator();
                        String user_name = "";
                        Integer id = null;
                        String user_password = "";
                        String perms = "";
                        String loginTime = "";
                        while (iterator.hasNext())
                        {
                            Map.Entry entry = (Entry) iterator.next();
                            if ("id".equals(entry.getKey().toString()))
                            {
                                id = (Integer) entry.getValue();
                            }
                            if ("name".equals(entry.getKey().toString()))
                            {
                                user_name = (String) entry.getValue();
                            }
                            if ("perms".equals(entry.getKey().toString()))
                            {
                                perms = (String) entry.getValue();
                            }
                            if ("login_time".equals(entry.getKey().toString()))
                            {
                                loginTime = entry.getValue().toString();
                            }
                        }
                        userMap.put("id", id);
                        userMap.put("name", request.getParameter("loginId"));
                        userMap.put("loginTime", loginTime.substring(0, loginTime.length() - 2));
                        userMap.put("perms", perms);
                        session.setAttribute("userMap", userMap);
                        // 修改登录时间
                        AdminEntity entiy = new AdminEntity();
                        entiy.setId(Long.parseLong(userMap.get("id").toString()));
                        entiy.setLoginTime(new Date());
                        this.adminDelegate.getAdminDao().updateUser(entiy);
                        return new ModelAndView("mainframe", userMap);
                    }
                    else if (!cver_code.equals(user_code))
                    {
                        log.info("invalid vcode.");
                        map.put("message", "验证码输入有误！");
                    }
                    else
                    {
                        log.info("invalid username and passwd. 2.");
                        map.put("message", "用户名或密码错误！");
                    }
                }
                else
                {
                    log.info("username and passwd were empty.");
                    map.put("message", "用户名和密码不能为空！");
                }
            }
            catch (Exception e)
            {
                log.error(e);
            }

        }
        return new ModelAndView("login", map);
    }

    /**
     * 退出登录
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView loginOut(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        HttpSession session = request.getSession(true);
        // 修改用户退出时间
        Map userMap = (Map) session.getAttribute("userMap");
        if (null != userMap)
        {
            try
            {
                AdminEntity entiy = new AdminEntity();
                entiy.setId(Long.parseLong(userMap.get("id").toString()));
                entiy.setLogoutTime(new Date());
                this.adminDelegate.getAdminDao().updateUser(entiy);
                // 删除session
                session.removeAttribute("userMap");
            }
            catch (Exception e)
            {
                log.error(e);
            }

        }
        return new ModelAndView("login");
    }

}
